package com.atguigu.tingshu.common.config;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;

@Configuration
@Slf4j
public class RabbitConfig {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        // 确认消息是否到达交换机，无论是否到达都会执行
        this.rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (!ack){
                log.error("消息没有到达交换机。原因：{}", cause);
            }
        });
        // 确认消息是否到达队列，只有未到达队列才会执行
        this.rabbitTemplate.setReturnsCallback(returned -> {
            log.error("消息没有到达队列。交换机：{}，路由键：{}，消息：{}",
                    returned.getExchange(), returned.getRoutingKey(), new String(returned.getMessage().getBody()));
        });
    }
}
